<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/8/10
 * Time: 16:07
 */

namespace app\api\validate;


use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    /**
     * 参数验证方法
     * @return bool
     * @throws Exception
     */
    public function goCheck(){
        $params = Request::instance()->param();
        $result = $this->batch()->check($params);
        if (!$result){
            $exception = new ParameterException([
                'msg'=>$this->error
            ]);
            throw  $exception ;
        }else{
            return true;
        }
    }
    /**
     *过滤非法参数
     * @param $arrays
     * @return array
     * @throws ParameterException
     */
    public function getDataByRule($arrays){
        if (array_key_exists('user_id',$arrays) | array_key_exists('uid',$arrays)){
            throw new ParameterException([
                'msg'=>'含有非法参数user_id或者uid'
            ]);
        }
        $newArray = [];
        foreach ($this->rule as $key=>$value){
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }
    /**
     * ID参数验证规则,必须为正整数
     * @param $value
     * @param string $rule
     * @param string $data
     * @param string $field
     * @return bool|string
     */
    protected function isPositiveInt($value,$rule='',$data='',$field=''){
        if (is_numeric($value) && is_int($value+0) && ($value + 0)>0 ){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 验证参数是否为空
     * @param $code
     * @return bool
     */
    protected function isNotEmpty($code){
        if (empty($code)){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 手机匹配
     * @param $mobile
     * @return bool
     */
    protected function isMobile($mobile){
        $rule = '^1(3|4|5|7|8|9)[0-9]\d{8}$^';
        $result = preg_match($rule,$mobile);
        if ($result){
            return true;
        }else{
            return false;
        }
    }

}